package sgi.client;

import java.io.IOException;

import sgi.message.MessageRegister;

public class SGIRegisterController extends SGIController {

	private static SGIRegisterController regControl;
	private static SGIRegisterUI regUI;
	
	public static SGIRegisterController createRegister()
	{
		if( SGIRegisterController.regControl == null )
		{
			SGIRegisterController.regControl = new SGIRegisterController();
			regUI.setRegController(regControl);
		}
		
		SGIRegisterController.regUI.setVisible(true);
		return SGIRegisterController.regControl;
	}
	
	private SGIRegisterController() 
	{
		SGIRegisterController.regUI = new SGIRegisterUI();
	}
	
	public static void terminate()
	{
		SGIRegisterController.regUI.setVisible(false);
		SGIRegisterController.regControl = null;
		SGIRegisterController.regUI = null;
	}

	public void register(String username,String password,String fname,String lname,String email,String phone) throws IOException
	{
		MessageRegister msg = new MessageRegister(username,password,fname,lname,email,phone);
		SGIClientConnectionController conn = SGIClientConnectionController.createConnection();
		try {
			conn.handleMessageFromClientUI(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static SGIRegisterUI getUI()
	{
		return regUI;
	}
	
	@Override
	void handleMessage(Object msg) {
		regUI.notify(((MessageRegister)msg).getNotif());
		if(((MessageRegister)msg).isValid() == true)
		{
			SGIRegisterController.terminate();
			try {
				SGILoginController.createLogin();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}
